package com.asiainfo.ncrm.base;

import com.asiainfo.ncrm.MainActivity;
import com.asiainfo.ncrm.common.Constant;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;


public class MyWebChromeClient extends WebChromeClient {
	private ValueCallback<Uri> mUploadMessage; // 上传文件时用
	
	private Activity nowact;

	public MyWebChromeClient(Activity act) {
		nowact = act;
	}

	public void myChooseFile() {
		this.openFileChooser(mUploadMessage, "", "");
	}

	@Override
	public boolean onJsAlert(WebView view, String url, String message,
			JsResult result) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(
				view.getContext());
		builder.setTitle("对话框").setMessage(message)
				.setPositiveButton("确定", null);
		AlertDialog dialog = builder.create();
		dialog.show();
		result.confirm();
		return true;
	}

	// For Android 3.0+
	public void openFileChooser(ValueCallback<Uri> uploadMsg,
			String acceptType) {
		this.openFileChooser(mUploadMessage, acceptType, "");
	}

	// For Android < 3.0
	public void openFileChooser(ValueCallback<Uri> uploadMsg) {
		this.openFileChooser(mUploadMessage, "", "");
	}

	// Android > 4.1.1 调用这个方法
	public void openFileChooser(ValueCallback<Uri> uploadMsg,
			String acceptType, String capture) {
		Log.d("BankkaActivity", "acceptType=" + acceptType + ",capture="
				+ capture);
		System.out.println("acceptType=" + acceptType + ",capture="
				+ capture);
		capture = null;
		mUploadMessage = uploadMsg;
		if ("camera".equalsIgnoreCase(capture)
				&& Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {// 有存贮卡的话，才走拍照
			// 拍照
			takePicture4InputFile();
		} else {
			if (capture == null
					&& (acceptType == null || acceptType
							.startsWith("image/"))
					&& Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
				showMenu4InputFile(acceptType);
			} else {
				// 文件选择
				chooseFile4InputFile(acceptType);
			}
		}
	}

	/**
	 * 显示选择菜单为Input File功能
	 * 
	 * @param acceptType
	 */
	/**
	 * 显示选择菜单为Input File功能
	 * 
	 * @param acceptType
	 */
	private void showMenu4InputFile(final String acceptType) {
		String[] menus = { "拍照", "相册" };
		Dialog dialog = new AlertDialog.Builder(nowact)
				.setItems(menus, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							takePicture4InputFile();
							break;
						case 1:
						default:
							chooseFile4InputFile(acceptType);
							break;
						}
					}
				}).create();

		// 这里很重要，如果弹出对话框，用户选择一个图片或者进行拍照，但是进行到一半的时候，用户cancel了，这个时候再去点击“选择文件”按钮时，网页会失去响应。
		// 原因是：点击“选择文件”按钮时，网页会缓存一个ValueCallback对象，必须触发了该对象的onReceiveValue()方法，WebView才会释放，进而才能再一次的选择文件。
		// 当弹层被取消时，返回未选择文件
		dialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				mUploadMessage.onReceiveValue(null);
				mUploadMessage = null;
			}
		});
		dialog.show();
	}

	/**
	 * 拍照为客户端的Input File功能
	 */
	private void takePicture4InputFile() {

		Intent takePictureIntent = new Intent(
				MediaStore.ACTION_IMAGE_CAPTURE);
		takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
				Constant.TEMP_IMAGE);
		nowact.startActivityForResult(takePictureIntent,
				Constant.DIRECT_SAVE_TO_SERVER);
	}

	/**
	 * 选择文件为客户端的Input File功能
	 */
	@SuppressLint("NewApi")
	private void chooseFile4InputFile(String acceptType) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE); // 能够返回一个Uri结果
		if (acceptType.isEmpty()) {// 接收类型
			acceptType = "*/*"; // 选择的文件类型，例如：image/*表示图片
		}
		intent.setType(acceptType);
		nowact.startActivityForResult(
				Intent.createChooser(intent, "File Chooser"),
				Constant.CHOISE_FILE);
	}
}
